package cool.taomu.toolkit.rpc.test

import cool.taomu.toolkit.Context
import cool.taomu.toolkit.TaomuConfigure
import cool.taomu.toolkit.TaomuGuice
import cool.taomu.toolkit.TaomuGuiceServiceLoader
import cool.taomu.toolkit.crypto.Base64
import cool.taomu.toolkit.rpc.test.TestService.Processor
import cool.taomu.toolkit.rpc.thrift.provider.TTransportPoolProvider
import cool.taomu.toolkit.rpc.thrift.server.module.ThritfTHsHaServerModule
import cool.taomu.toolkit.rpc.thrift.server.service.TaomuThriftTHsHaServer
import cool.taomu.toolkit.rpc.thrift.service.ThriftConnectionFactory
import org.apache.thrift.TException
import org.apache.thrift.protocol.TCompactProtocol
import org.apache.thrift.transport.layered.TFramedTransport
import org.junit.jupiter.api.Test

class ThriftTest {

    static class TestIface implements TestService.Iface {

        override sayHello(String name) throws TException {
            return "Hello " + name
        }

        def static getProcessor() {
            new Processor(new TestIface());
        }

        override ping() throws TException {
            "PONG"
        }

    }

    @Test
    def void b() {
        val TaomuConfigure config = new TaomuConfigure(new Base64())
        config.loadConfig
        var injector = TaomuGuice.createInjector(config)
        TaomuGuiceServiceLoader.loadIPlatform(injector, config)
        var context = injector.getInstance(Context);
        var cjnjector = context.injectorSupplier.get().createChildInjector(new ThritfTHsHaServerModule())
        val map = cjnjector.getInstance(TaomuThriftTHsHaServer)
        new Thread(new Runnable() {
            override run() {
                map.get("a", TestIface.processor).serve
            }
        }).start();
        var factory = new ThriftConnectionFactory("127.0.0.1", 18080, 3000, [ socket |
            var tTransport = new TFramedTransport(socket, Integer.MAX_VALUE)
            var protocol = new TCompactProtocol(tTransport);
            var client = new TestService.Client(protocol);
            client.ping().equals("PONG");
        ]);

        var pool = factory.getObjectPool(new TTransportPoolProvider().get());
        var socket = pool.borrowObject;
        try (var tTransport = new TFramedTransport(socket,  Integer.MAX_VALUE)) {
            var protocol = new TCompactProtocol(tTransport);
            var client = new TestService.Client(protocol);
            println(client.sayHello("Thritf!!!"))
        }
        pool.returnObject(socket)
        while (true) {
        }
    }
}
